import re
from collections import defaultdict
class TagParser:
    def __init__(self):
# 正则匹配行内容：层级标记、键值对、井号字符串
        self.line_pattern = re.compile(r'^(\d+)([a-z]+)\.(.*?)(#(.*?)#)?$')
        self.comment_pattern = re.compile(r'^#|^#\d')
    def parse(self, text):
        result = defaultdict(dict)
        current_scope = [result]  # 当前作用域栈
        last_num = 0
        for line in text.split('\n'):
            line = line.strip()
            if not line or self.comment_pattern.match(line):
                continue  # 跳过注释和空行‌:ml-citation{ref="1" data="citationList"}
# 解析井号包裹的字符串
            if '#' in line:
                value = re.search(r'#(.*?)#', line)
                if value:
                    line = line.replace(value.group(0), value.group(1))
# 匹配层级和键值
            match = self.line_pattern.match(line)
            if not match:
                continue
                num_part, alpha_part, rest, _, _ = match.groups()
            num = int(num_part)
# 处理层级变化
            if num > last_num:  # 进入新层级
current_scope.append(current_scope[-1].setdefault('children', {}))
            elif num < last_num:  # 返回上层级
                current_scope = current_scope[:num]
# 拆分键值对
            key, *values = rest.split('.', 1) 
            value = values if values else '' 
# 更新当前作用域
            current_scope[-1][key.strip('. ')] = value.strip()
            last_num
        return result
def print_result(data, indent=0):
    for k, v in data.items():
        if isinstance(v, dict):
            print(' ' * indent + k)
            print_result(v, indent + 4)
        else:
            print(' ' * indent + f"{k}:{v}")
# 测试用例
text = """
1a.Person.
1b.name.johnny.
2b.age.45.
3b.intro.#here's Johnny!
1a.#so...#.
# 这是一行注释
1a.#bilibili.com#.
"""
parser = TagParser()
result = parser.parse(text)
print_result(result)